﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SimpleNotify.PushLibrary.NotifyService;
using System.ServiceModel;
using SimpleNotify.PushLibrary.Translators;

namespace SimpleNotify.PushLibrary
{
    public class PushClient : IServiceCallback
    {
        private string _notifyServer = String.Empty;

        public PushClient(string notifyServer)
        {
            _notifyServer = notifyServer;
        }

        private ServiceClient CreateProxy()
        {
            string endpointAddress = String.Format("http://{0}:80/Service.svc", _notifyServer);

            WSDualHttpBinding binding = new WSDualHttpBinding(WSDualHttpSecurityMode.None);
            binding.OpenTimeout = new TimeSpan(0, 0, 30);
            binding.CloseTimeout = new TimeSpan(0, 0, 30);
            binding.ReceiveTimeout = new TimeSpan(0, 5, 0);
            binding.CloseTimeout = new TimeSpan(0, 0, 30);
            ServiceClient proxy = new ServiceClient(new InstanceContext(this), binding, new EndpointAddress(endpointAddress));
            return proxy;
        }

        public PushResult PushMessageToClient(string client, string title, string text, NotificationType type, string data)
        {
            ServiceClient proxy = CreateProxy();
            NotifyService.PushResult response = proxy.PushMessageToClient(client, title, text, NotificationTypeTranslator.EntityToDataContract(type), data);
            PushResult result = PushResultTranslator.DataContractToEntity(response);
            proxy.Close();
            return result;
        }

        public PushResult[] PushMessageToMany(string[] clients, string title, string text, NotificationType type, string data)
        {
            ServiceClient proxy = CreateProxy();
            NotifyService.PushResult[] response = proxy.PushMessageToMany(clients, title, text, NotificationTypeTranslator.EntityToDataContract(type), data);
            PushResult[] result = PushResultArrayTranslator.DataContractToEntity(response);
            proxy.Close();
            return result;
        }

        public string[] GetSubscribers()
        {
            ServiceClient proxy = CreateProxy();
            string[] result = proxy.GetSubscribers();
            proxy.Close();
            return result;
        }

        public bool Notify(string title, string text, NotifyService.NotificationType type, string data)
        {
            throw new NotImplementedException("Not needed in here");
        }
    }
}
